// page/Home.js
const db = wx.cloud.database()
const {
    hourSpendList,
    cardType
} = require('../config/map')
const {
    formatDate
} = require('../../util/util')
let isLoadCourseData = false
Page({
    /**
     * 页面的初始数据
     */
    data: {
        pagination: {
            pageSize: 1,
            pageNum: 10,
        },
        pushCardObj: {
            cardType: {
                value: '1',
                text: "上课"
            },
            hourSpend: {
                value: '1',
                text: "1课时"
            },
            schoolTime: new Date().getTime(),
            remark: ""
        },
        cardAndSpendShow: false,
        hourSpendList,
        cardType,
        pushCardShow: false,
        total: 0,
        courses: [],
        curType: '',
        curCommonList: [],
        isPushCard: false,
        schoolTime: false,
        curCourse: null,
        curCommonIndex: 0
    },
    edit() {

    },
    record(data) {
        console.log(data);
        wx.navigateTo({
          url: '/page/list/list?id='+data.detail.data._id,
        })
    },
    async createPushCardRecord() {
        const {
            curCourse,
            pushCardObj
        } = this.data
        if (!curCourse) return

        if (pushCardObj.cardType.value !== '2') {
            const res = await db.collection('course').where({
                _id: curCourse._id,
            }).get()
            if (res.errMsg === 'collection.get:ok') {
                if (Number(res.data[0].resetHour) < Number(pushCardObj.hourSpend.value)) {
                    wx.showToast({
                        title: '剩余课时不足',
                        icon: 'error',
                        duration: 2000
                    })
                    return
                }
                let resUpdata = await db.collection('course').where({
                    _id: curCourse._id
                }).update({
                    data: {
                        resetHour: res.data[0].resetHour - pushCardObj.hourSpend.value
                    },
                })
                if (resUpdata.errMsg === 'collection.update:ok') {
                  console.log(resUpdata);
                    let resAdd = await db.collection('course_list').add({
                        data: {
                            course_id: curCourse._id,
                            ...pushCardObj,
                            cardDate: formatDate(new Date().getTime()),
                            name:res.data[0].courseName,
                            timeLine:res.data[0].schoolTime,
                        }
                    })
                    if (resAdd.errMsg === 'collection.add:ok') {
                        wx.showToast({
                            title: '成功',
                            icon: 'success',
                            duration: 2000
                        })
                        this.refreshData();
                        this.setData({
                            pushCardShow: false
                        })
                    }
                }
            }
        } else {
            let resAdd = await db.collection('course_list').add({
                data: {
                    course_id: curCourse._id,
                    ...pushCardObj,
                    cardDate: formatDate(new Date().getTime())
                }
            })
            if (resAdd.errMsg === 'collection.add:ok') {
                wx.showToast({
                    title: '成功',
                    icon: 'success',
                    duration: 2000
                })
                this.refreshData();
                this.setData({
                    pushCardShow: false
                })
            }
        }

    },
    onChangeRemark(e) {
        const {
            pushCardObj,
        } = this.data
        pushCardObj.remark = e.detail
        this.setData({
            pushCardObj
        })
    },
    schoolTimeHandler() {
        this.setData({
            schoolTime: true,
            type: 'schoolTime'
        })
    },
    onCancelCommon() {
        this.setData({
            cardAndSpendShow: false,
            schoolTime: false
        })
    },
    onConfirmCommon(e) {
        const {
            pushCardObj,
            curType,
        } = this.data
        console.log(e);
        if (curType === 'pushCard') {
            pushCardObj.cardType = e.detail.value
            this.setData({
                pushCardObj,
                cardAndSpendShow: false
            });
        } else if (curType === 'spendHour') {
            pushCardObj.hourSpend = e.detail.value
            this.setData({
                pushCardObj,
                cardAndSpendShow: false
            });
        } else {
            console.log('xiugai ');
            pushCardObj.schoolTime = e.detail
            this.setData({
                pushCardObj,
                schoolTime: false
            });
        }
    },
    popupCommon(e) {
        const {
            type,
        } = e.currentTarget.dataset
        let {
            hourSpendList,
            cardType
        } = this.data
        if (type === 'pushCard') {
            this.setData({
                curType: type,
                curCommonList: cardType,
                cardAndSpendShow: true
            })
        } else {
            this.setData({
                curType: type,
                curCommonList: hourSpendList,
                cardAndSpendShow: true
            })
        }

    },
    async signIn(data) {
        let {
            pushCardObj,
            cardType: curCardType
        } = this.data
        pushCardObj.hourSpend = data.detail.data.hourSpend

        let course_list = await db.collection('course_list').where({
            course_id: data.detail.data._id,
            cardDate: formatDate(new Date().getTime()),
            cardType: {
                text: '上课',
                value: '1'
            }
        }).get()
        if (course_list.data.length > 0) {
            curCardType = curCardType.filter(val => val.value === '3')
            pushCardObj.cardType = {
                value: '3',
                text: '补卡',
            }
        } else {
            curCardType = cardType
            pushCardObj.cardType = {
                value: '1',
                text: '上课',
            }
        }
        this.setData({
            pushCardShow: true,
            curCourse: data.detail.data,
            pushCardObj,
            cardType: curCardType
        })

    },
    onClose() {
        this.setData({
            pushCardShow: false
        })
    },
    async getTotal() {
        const countResult = await db.collection('course').count();
        this.setData({
            total: countResult.total
        })
    },
    scrollEnd() {
        console.log('scrollend');
        const {
            pagination
        } = this.data
        pagination.pageSize++;
        this.setData({
            pagination
        }, () => {
            if (!isLoadCourseData) {
                console.log('加载数据');
                this.getData()
            }
        })
    },
    async getData() {
        if (this.data.courses.length >= this.data.total) return
        const {
            pagination,
            courses
        } = this.data
        isLoadCourseData = true
        db.collection('course').orderBy('createTime', 'desc').limit(pagination.pageNum).skip((pagination.pageSize - 1) * pagination.pageNum).get().then(res => {
            courses.push(...res.data)
            this.setData({
                courses
            })
            isLoadCourseData = false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        getApp().globalData.pageHome = this;
        await this.getTotal()
        this.getData();
    },
    refreshData: function () {
        this.setData({
            pagination: {
                pageSize: 1,
                pageNum: 10,
            },
            total: 0,
            courses: []
        }, async () => {
            await this.getTotal()
            this.getData();
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('被加载');
    },

});